import {
	resPost
} from "../common/http.request";
import store from "../store";
import qs from 'qs'
// 环迅支付
export function huanxunPay(obj) {
	return new Promise((resolve, reject) => {
		let params = {
			order_no: obj.order_no,
		}
		// #ifdef H5
		params = {
			...params,
			openid: store.state.vuex_user.openid,
		}
		// #endif
		// #ifdef MP-WEIXIN
		params = {
			...params,
			openid: store.state.vuex_user.small_routine,
		}
		// #endif
		// #ifdef APP-PLUS
		params = {
			...params,
			openid: store.state.vuex_user.otherid,
		}
		// #endif
		// typetype:22
		resPost('SetTradePlatformPay', params, {}).then(({ data }) => {
			payOrder(data).then((res) => {
				resolve(res)
			}).catch(() => {
				reject('支付失败')
			})
		}).catch((err) => {
			console.log('errrr001', params)
			reject()
		})
	})
}

// #ifdef H5 || MP-WEIXIN
export function wxPay(obj) {
	return new Promise((resolve, reject) => {
		let params = {
			mch_id: store.state.vuex_business.mchid,
			body: obj.prodName || store.state.vuex_business.name,
			sign_key: store.state.vuex_business.payment_key,
			out_trade_no: obj.order_no,
			total_fee: obj.total_fee,
			appid: store.state.vuex_business.appid,
			...obj.parameter_obj,
		}
		// #ifdef H5
		params = {
			...params,
			openid: store.state.vuex_user.openid,
		}
		// #endif
		// #ifdef MP-WEIXIN
		params = {
			...params,
			openid: store.state.vuex_user.small_routine,
		}
		// #endif
		resPost(obj.createPayApi || 'GetCreateOrderPay', params).then(({
			data
		}) => {
			payOrder(data).then((res) => {
				resolve(res)
			}).catch(() => {
				reject('支付失败')
			})
		}).catch((err) => {
			reject()
		})
	})
}
// #endif

// 银联直接支付
export function yinlianPay(obj) {
	return new Promise((resolve, reject) => {
		let params = {
			appid: store.state.vuex_business.appid,
			money: obj.total_fee,
			order_no: obj.order_no
		}
		// #ifdef H5
		params.openid = store.state.vuex_user.openid,
			// #endif
			// #ifdef MP-WEIXIN
			params.openid = store.state.vuex_user.small_routine,
			// #endif
			// #ifdef APP-PLUS
			params.openid = store.state.vuex_user.otherid,
			// #endif
			resPost('UnionPayPayment', params).then(({
				data
			}) => {
				payOrder(data).then((res) => {
					resolve(res)
				}).catch(() => {
					reject('支付失败')
				})
			}).catch(() => {
				reject()
			})
	})
}

// #ifdef APP-PLUS
// APP 微信支付
export function wxPay(obj) {
	return new Promise((resolve, reject) => {
		let params = {
			mch_id: store.state.vuex_business.mchid,
			body: obj.prodName || store.state.vuex_business.name,
			sign_key: store.state.vuex_business.payment_key,
			out_trade_no: obj.order_no,
			total_fee: obj.total_fee,
			appid: store.state.vuex_business.appid,
			openid: store.state.vuex_user.otherid,
		}
		console.log('获取支付准备1', params)
		resPost('GetAppCreateOrderPay', params).then(({
			data
		}) => {
			payOrder(data).then((res) => {
				resolve(res)
			}).catch(() => {
				reject('支付失败')
			})
		}).catch((err) => {
			reject()
		})
	})
}
// APP 支付宝支付
export function alipay(obj) {
	return new Promise((resolve, reject) => {
		let params = {
			appid: store.state.vuex_businessObj.alipayappid,
			order_no: obj.order_no,
			total_amount: obj.total_fee
		}
		resPost('AlipayTradeAppPayCreate', params).then(({
			data
		}) => {
			console.log(data)
			payOrder(data, true).then((res) => {
				resolve(res)
			}).catch(() => {
				reject('支付失败')
			})
		}).catch((err) => {
			console.log(err)
			reject()
		})
	})
}
// #endif

// #ifdef  MP-ALIPAY
// 支付宝小程序支付
export function alipay(obj, opts) {
	return new Promise((resolve, reject) => {
		let params = {
			name: obj.prodName || store.state.vuex_business.name,
			appid: store.state.vuex_business.appid,
			order_no: obj.order_no,
			openid: store.state.vuex_user.otherid,
			total_amount: obj.total_fee,

		}

		if (opts.appid || opts.store_id) {
			params.appid = opts.appid
			params.store_id = opts.store_id
		}

		resPost('AlipayTradeCreate', params).then(({
			data
		}) => {
			my.tradePay({
				tradeNO: data.trade_no,
				success: (res) => {
					setTimeout(() => {
						AlipayTradeQuery(obj.order_no, opts).then(() => {
							resolve()
						}).catch((err) => {
							reject(err)
						})
					}, 1000)
				},
				fail: (err) => {
					reject()
				}
			});
		}).catch((err) => {
			console.log(err)
			reject()
		})
	})
}
// 查询用户是否在支付宝 支付成功
function AlipayTradeQuery(order_no, opts) {
	return new Promise((resolve, reject) => {

		let params = { //查询订单状态
			order_no,
			appid: store.state.vuex_business.appid,
		}

		if (opts.appid || opts.store_id) {
			params.appid = opts.appid
			params.store_id = opts.store_id
		}

		resPost('AlipayTradeQuery', params).then(res => {
			if (res.data.pay_status == "TRADE_SUCCESS") {
				resolve()
				return
			}
			reject('支付失败')
		}).catch(err => {
			reject(err)
		})
	})
}
// #endif

// #ifdef  MP-BAIDU	

export function baiduPay(data) {

	return new Promise((resolve, reject) => {
		resPost('GetBaiduSmartPay', {
			appid: store.state.vuex_business.appid,
			order_no: data.order_no,
			pay_amount: data.total_fee,
			users_id: undefined,
			business_id: undefined,

		}).then(res => {
			BDPay({
				...res.data.openid,
				order_no: data.order_no
			}).then(res1 => {
				resPost('FindByTpOrderId', { //查询订单状态
					appid: store.state.vuex_business.appid,
					order_no: data.order_no,
				}).then(res2 => {
					let row = JSON.parse(JSON.parse(res2.data.openid))
					if (row.data && row.data.status == 2) {
						resolve(row.data)
						return
					}
					reject()
				}).catch((err) => {
					console.log(err)
					reject()
				})



			}).catch((err) => {
				console.log(err)
				reject()
			})

		})
	})
}

// #endif



/**
 * h5端支付
 */
// #ifdef H5
export function payOrder(payParams) {
	return new Promise((resolve, reject) => {
		const onBridgeReady = () => {
			WeixinJSBridge.invoke('getBrandWCPayRequest', {
				"appId": payParams.appId, //公众号名称，由商户传入
				"timeStamp": payParams.timeStamp, //时间戳，自1970年以来的秒数
				"nonceStr": payParams.nonceStr, //随机串
				"package": payParams.package,
				"signType": payParams.signType, //微信签名方式：
				"paySign": payParams.paySign //微信签名
			}, function(res) {
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					// 使用以上方式判断前端返回,微信团队郑重提示：
					//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
					resolve()
				} else {
					reject()
				}
			});
		}
		if (typeof WeixinJSBridge == "undefined") {
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', onBridgeReady(), false);
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', onBridgeReady());
				document.attachEvent('onWeixinJSBridgeReady', onBridgeReady());
			}
		} else {
			onBridgeReady();
		}
	})
}
// #endif
/**
 * 微信小程序端:微信支付、环迅支付
 * app :微信支付 支付宝支付
 */
// #ifdef MP-WEIXIN || APP-PLUS
export function payOrder(params, isALIPAY = false) {
	return new Promise((resolve, reject) => {
		let newParams = {}
		// #ifdef MP-WEIXIN
		newParams = {
			'timeStamp': params.timeStamp,
			'nonceStr': params.nonceStr,
			'package': params.package,
			'signType': params.signType,
			'paySign': params.paySign,
		}
		// #endif
		// #ifdef APP-PLUS
		if (isALIPAY) {
			newParams = {
				provider: 'alipay',
				orderInfo: params.trade_no
			}
		} else {
			newParams = {
				provider: 'wxpay',
				orderInfo: {
					...params
				}
			}
		}
		// #endif
		console.log('支付参数2', newParams)
		uni.requestPayment({
			...newParams,
			'success': res => {
				console.log('res')
				resolve(res)
			},
			'fail': err => {
				console.log('err', err)
				reject(err)
			}
		})
	})
}
// #endif

// #ifdef MP-BAIDU
export function BDPay(params, order_no) {
	return new Promise((resolve, reject) => {
		swan.requestPolymerPayment({
			orderInfo: params,
			success(res) {
				resolve(res)

			},
			fail(res) {
				console.log(res, '失败了')
				reject(res)
			}
		})
	})
}

function getBaiduPayInfo(params) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `https://baidumini.kailly.com/ApiBaidu/RequestPayment${qs.stringify(params, {addQueryPrefix: true})}`,
			method: 'POST',
			data: {},
			timeout: 6000,
			header: {
				'content-type': 'application/json; charset=utf-8'
			},
			success(res) {
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}
// #endif


// #ifdef MP-TOUTIAO	

export function TTPay(data) {

	return new Promise((resolve, reject) => {
		resPost('GetTiktokCreateOrder', {
			appid: store.state.vuex_business.appid,
			order_no: data.order_no,
			payment_key: store.state.vuex_business.payment_key,
			total_amount: data.total_fee,
			users_id: undefined,
			business_id: undefined,

		}).then(res => {

			TouTiaoPay(JSON.parse(res.data).data).then(() => {
				resPost('GetTiktokQueryOrder', { //查询订单状态
					appid: store.state..appid,
					payment_key: store.state.vuex_business.payment_key,
					order_no: data.order_no,
				}).then(res2 => {
					let {
						payment_info
					} = JSON.parse(res2.data)
					if (payment_info.order_status == 'SUCCESS') {
						resolve()
						return
					}
					reject()
				})

			}).catch((err) => {
				reject()
				console.log(err, '支付失败')
			})

		}).catch((err) => {
			console.log(err, '获取抖音支付信息失败')
			reject()
		})

	})

}




function TouTiaoPay(orderInfo) {
	return new Promise((resolve, reject) => {
		tt.pay({
			orderInfo,
			service: 5,
			success(res) {
				if (res.code === 0) {
					resolve()
					return
				}
				reject()
			},
			fail(err) {
				console.log(err, '支付失败')
				reject()

			},

		});
	})
}

// #endif
